package com.sky.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private JwtProperties jwtProperties;


    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //根据前端传递来的用户凭证向微信端获取openid等信息
        String openid=getOpenid(userLoginDTO.getCode());

        //判断是否获取成功
        if (openid==null){
            throw new UserNotLoginException(MessageConstant.LOGIN_FAILED);
        }

        //判断本地数据库是否储存这个用户的信息,没有储存的话进行存储
        if (userMapper.selectByOpenid(openid)==null){
            User user=new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        //查询出dto对象返回
        User user=userMapper.selectByOpenid(openid);
        UserLoginVO loginVO=new UserLoginVO();
        BeanUtils.copyProperties(user,loginVO);

        //生成jwt令牌
        Map<String,Object>jwtMap=new HashMap<>();
        jwtMap.put("openid",openid);
        jwtMap.put("userId",user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), jwtMap);
        loginVO.setToken(jwt);

        return loginVO;
    }

    private String getOpenid(String code) {

        Map<String,String>wxMap=new HashMap<>();
        wxMap.put("appid",weChatProperties.getAppid());
        wxMap.put("secret",weChatProperties.getSecret());
        wxMap.put("js_code",code);
        wxMap.put("grant_type","authorization_code");

        //生成httpclient对象
        String objectJson = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", wxMap);

        //将json对象解析出来
        JSONObject jsonObject = JSON.parseObject(objectJson);

        return jsonObject.getString("openid");
    }
}
